package com.Shoping.dao.impl;

import com.Shoping.dao.UserDao;
import com.Shoping.entity.User;
import com.Shoping.util.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner = new QueryRunner();

    @Override
    public User selectByNamePwd(String userName, String password) throws SQLException {
        String sql = "SELECT u_id uId,o_number oNumber,s_id sId,\n" +
                "u_username uUsername,u_password uPassword,u_name uName,\n" +
                "u_birthday uBirthday,u_sex uSex,u_img uImg,u_category uCategory,\n" +
                "u_area uArea FROM USER WHERE u_username=? AND u_password=?;";
        return queryRunner.query(DbUtils.getConnection(), sql, new BeanHandler<User>(User.class), userName, password);
    }

    @Override
    public User selectByUsername(String userCode) throws SQLException {
        String sql = "SELECT u_id uId,o_number oNumber,s_id sId,\n" +
                "u_username uUsername,u_password uPassword,u_name uName,\n" +
                "u_birthday uBirthday,u_sex uSex,u_img uImg,u_category uCategory,\n" +
                "u_area uArea FROM USER WHERE u_username=?;";
        return queryRunner.query(DbUtils.getConnection(), sql, new BeanHandler<User>(User.class), userCode);
    }

    @Override
    public void createUser(String userCode, String newPassword) throws SQLException {
        String sql = "INSERT INTO USER(u_username,u_password) VALUES(?,?);";
        queryRunner.update(DbUtils.getConnection(), sql, userCode, newPassword);
    }

    @Override
    public void updatePassowrd(String password, Integer uid) throws SQLException {
        String sql = "UPDATE USER SET u_password=? WHERE u_id=?;";
        queryRunner.update(DbUtils.getConnection(), sql, password, uid);
    }
}
